package com.vrv.netmgr.database.downservice;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.ContentValues;
import android.util.Log;

import com.vrv.common.GlobalConstants;
import com.vrv.common.resolver.Page;
import com.vrv.common.resolver.RequestParameter;
import com.vrv.common.resolver.Response;
import com.vrv.common.resolver.remote.RequestUtils;
import com.vrv.common.util.DateUtils;
import com.vrv.netmgr.database.TypeConfig;
import com.vrv.netmgr.database.dao.EquipmentChangedDao;
import com.vrv.netmgr.database.dao.UpdateLogDao;
import com.vrv.netmgr.database.table.UpdateLog;

/**
 * 设备变化后台更新主要处理逻辑 时间戳定义为报警时间 每次更新前获取上次更新的时间戳，发送到服务器端，由服务器端决定是否返回数据
 *
 * @author zxb
 *
 */
public class EquipmentChangedDown {
    private static final String TAG = EquipmentChangedDown.class.getSimpleName();
    private static final boolean DEBUG = true && GlobalConstants.DEBUG;

    public static void startCache() {
        if (DEBUG)
            Log.e(TAG, "startCache()");

        // 获取上次更新时间戳
        String lastTime = getLastTime();
        if (null == lastTime) {
            lastTime = "";
        }

        RequestParameter parameter = new RequestParameter("/errorMessage/jsonList.do?errorType=1");
        parameter.addArgs("errorMsg", "");
        parameter.addArgs("ipaddress", "");
        parameter.addArgs("lastTime", lastTime);

        // 数据库对应字段
        String[] detailKeys = new String[] { "deptName", "officeName", "userName", "tel", "ipaddress", "deviceName", "ipaddress1", "errorMsg", "sysUserName", "errorTime", "macAddress", "lookFlag" };

        Page page = null;

        // 首次查询
        // Response response = RequestUtils.getInstance().request(parameter,
        // detailKeys);
        String resultString1 = RequestUtils.getInstance().request(parameter, detailKeys);
        Response response1 = RequestUtils.getInstance().parse(resultString1, detailKeys);
        if (response1.isSuccess() && response1.getTotalRecords() > 0 && response1.getRecords() != null && response1.getRecords().size() > 0) {
            page = new Page(response1);
            // 存储数据库
            save(response1.getRecords(), lastTime);
        } else {
            return;
        }

        // 分页查询
        while (page.hasNextPage()) {
            int pageNumber = page.getPageNumber() + 1;
            parameter.addArgs("pageNumber", pageNumber);
            // response = RequestUtils.getInstance().request(parameter,
            // detailKeys);
            String resultString2 = RequestUtils.getInstance().request(parameter, detailKeys);
            Response response2 = RequestUtils.getInstance().parse(resultString2, detailKeys);

            if (response2.isSuccess() && response2.getTotalRecords() > 0 && response2.getRecords() != null && response2.getRecords().size() > 0) {
                page = new Page(response2);
                // 存储数据库
                save(response2.getRecords(), lastTime);
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static String getLastTime() {
        if (DEBUG)
            Log.e(TAG, "getLastTime()");

        String time = UpdateLogDao.findTimeByType(TypeConfig.EQUIPMENT_CHANGED);
        return time;
    }

    /**
     * 保存数据库操作
     *
     * @param list
     * @return
     */
    public static void save(List<Map<String, Object>> list, String lastTime) {
        if (DEBUG)
            Log.e(TAG, "save()");

        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);

            ContentValues values = new ContentValues();

            Set<String> keys = map.keySet();
            for (Iterator<String> it = keys.iterator(); it.hasNext();) {
                String key = (String) it.next();
                if (null == key || key.equals("")) {
                    continue;
                }
                Object value = map.get(key);
                if (null == value || value.toString().equals("null")) {
                    value = "";
                }

                String sValue = value.toString();
                values.put(key, sValue);
            }

            EquipmentChangedDao.save(values);

            // 日志处理
            long lLastTime = 0;
            long lErrorTime = 0;

            if (null != lastTime && lastTime.equals("")) {
                lLastTime = DateUtils.getLongDate(lastTime);
            }

            Object obj = map.get("errorTime");
            if (null != obj) {
                String errorTime = obj.toString();
                lErrorTime = DateUtils.getLongDate(errorTime);
            }

            if (lLastTime < lErrorTime) {
                UpdateLog uLog = new UpdateLog();
                uLog.setMode(TypeConfig.EQUIPMENT_CHANGED);
                uLog.setTime(obj.toString());
                UpdateLogDao.insert(uLog);
            }
        }
    }
}
